﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Utils.Encryption
{
   public class TripleDESHelper
    {
        #region  使用 给定密钥 加密/解密/byte[]  

        /// <summary>  
        /// 生成MD5摘要  
        /// </summary>  
        /// <param name="original">数据源</param>  
        /// <returns>摘要</returns>  
        public static byte[] MakeMD5(byte[] original)
        {
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            byte[] keyhash = hashmd5.ComputeHash(original);
            hashmd5 = null;
            return keyhash;
        }

        /// <summary>  
        /// 使用给定密钥加密  
        /// </summary>  
        /// <param name="original">明文</param>  
        /// <param name="key">密钥</param>  
        /// <returns>密文</returns>  
        public static byte[] Encrypt(byte[] original, byte[] key)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            des.Key = MakeMD5(key);
            des.Mode = CipherMode.ECB;

            return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length);
        }

        /// <summary>  
        /// 使用给定密钥解密数据  
        /// </summary>  
        /// <param name="encrypted">密文</param>  
        /// <param name="key">密钥</param>  
        /// <returns>明文</returns>  
        public static byte[] Decrypt(byte[] encrypted, byte[] key)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            des.Key = MakeMD5(key);
            des.Mode = CipherMode.ECB;

            return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length);
        }

        #endregion
    }
}
